package com.kll.tv.views

import android.content.Intent
import android.text.InputType
import android.view.View
import android.widget.Toast
import com.google.i18n.phonenumbers.PhoneNumberUtil
import com.kll.carolinehmibiz.OperationManager
import com.kll.carolinehmibiz.model.AccountModel
import com.kll.carolinehmibiz.model.OperateListener
import com.kll.carolinehmibiz.net.bean.RefreshTokenResponse
import com.kll.carolinehmibiz.presentation.listener.LoginProtocol
import com.kll.carolinehmibiz.presentation.presenter.LoginPresenter
import com.kll.tv.base.views.BaseActivity
import com.kll.tv.databinding.ActivityLoginBinding
import com.kll.tv.utils.AppToast
import com.tencent.qcloud.tuicore.util.SoftKeyBoardUtil

/**
 * 登录页
 */
class LoginActivity: BaseActivity<LoginPresenter>(), LoginProtocol.IView {
    private lateinit var binding: ActivityLoginBinding
    private var mobile = ""
    private var verifyCode = ""
    private var password = ""
    private var loginMode = 0 // 0-验证码登录 1-密码登录

    override fun initViewBinding(): View {
        binding = ActivityLoginBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createPresenter(): LoginPresenter {
        return LoginPresenter(this, this)
    }

    override fun init() {

        initListener()
    }

    private fun initListener() {

        // 获取验证码
        binding.tvGetCheckingCode.setOnClickListener {
            mobile = binding.edtPhoneNumber.text.toString().trim()

            // 判断
            var isValidate = false
            if (mobile.length > 8){
                // 校验手机号码
                isValidate = PhoneNumberUtil.getInstance().isValidNumber(PhoneNumberUtil.getInstance().parse(mobile, "CN"))
            }
            if (!isValidate) {
                AppToast.show("请输入正确的手机号码！", 2000)
                return@setOnClickListener
            }

            mPresenter.getVerifyCode(mobile)
        }

        // 登录
        binding.tvSubmit.setOnClickListener {
            if(!binding.cbAgree.isChecked){
                AppToast.show("请先阅读并同意隐私政策", Toast.LENGTH_LONG);
                return@setOnClickListener;
            }
            if (loginMode == 0) {
                mobile = binding.edtPhoneNumber.text.toString().trim()
                verifyCode = binding.edtVerifyCode.text.toString().trim()

                // 判断
                var isValidate = false
                if (mobile.length > 8){
                    // 校验手机号码
                    isValidate = PhoneNumberUtil.getInstance().isValidNumber(PhoneNumberUtil.getInstance().parse(mobile, "CN"))
                }
                if (!isValidate) {
                    AppToast.show("请输入正确的手机号码！", 2000)
                    return@setOnClickListener
                }
                if (verifyCode.length < 4) {
                    AppToast.show("请输入正确的验证码！", 3000)
                    return@setOnClickListener
                }

                // 登录
                mPresenter.login(mobile, verifyCode)
            } else {
                AppToast.show("该功能在开发中！", 2000)
            }
        }

        // 密码登录 or 验证码登录
        binding.tvPasswordVerify.setOnClickListener {
            if (loginMode == 0) {
                loginMode = 1
                binding.tvPasswordVerify.text = "验证码登录"
                binding.edtVerifyCode.hint = "请输入密码"
                binding.edtVerifyCode.inputType = InputType.TYPE_TEXT_VARIATION_PASSWORD
                binding.tvGetCheckingCode.visibility = View.GONE
            } else {
                loginMode = 0
                binding.tvPasswordVerify.text = "密码登录"
                binding.edtVerifyCode.hint = "请输入验证码"
                binding.edtVerifyCode.inputType = InputType.TYPE_CLASS_NUMBER
                binding.tvGetCheckingCode.visibility = View.VISIBLE
            }
        }

        // 忘记密码
        binding.tvForgetPassword.setOnClickListener {
            startActivity(Intent(this, ForgetPasswordActivity::class.java))
        }

        binding.edtPhoneNumber.setOnFocusChangeListener(object : View.OnFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (!hasFocus) {
                    SoftKeyBoardUtil.hideKeyBoard(binding.edtPhoneNumber.windowToken)
                } else {
                    SoftKeyBoardUtil.showSoftInput(binding.edtPhoneNumber)
                }
            }

        })
        binding.edtVerifyCode.setOnFocusChangeListener(object : View.OnFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (!hasFocus) {
                    SoftKeyBoardUtil.hideKeyBoard(binding.edtVerifyCode.windowToken)
                } else {
                    SoftKeyBoardUtil.showSoftInput(binding.edtVerifyCode)
                }
            }

        })
        binding.tvPrivacy.setOnClickListener {
            startActivity(
                Intent(this, ExternalLinksDetailsActivity::class.java).putExtra("menuTitle", "隐私政策")
                    .putExtra("url", "http://app.huaxia-health.com/static/yinsizhengce.html")
            )
        }
    }

    override fun showLoading() {

    }

    override fun stopLoading() {

    }

    override fun loginFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                    mPresenter.login(mobile, verifyCode)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    override fun loginSuccessed() {
        AppToast.show("登录成功！", 2000)
        startActivity(Intent(this, MainActivity::class.java))
    }

    override fun sendVerifyCodeSuccessed() {
        AppToast.show("获取验证码成功！", 2000)
    }

    override fun sendVerifyCodeFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                    mPresenter.getVerifyCode(mobile)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    /**
     * 更改验证码倒计时ui回调
     */
    override fun loadAreaCodeTime(count: String, isBusying: Boolean) {
        if (isBusying) {
            binding.tvGetCheckingCode.text = count + "秒后发送"
        } else {
            binding.tvGetCheckingCode.text = count
        }
    }
}